package com.buba.service.Impl;

import com.buba.mapper.FriendMapper;
import com.buba.mapper.MessageMapper;
import com.buba.service.MessageService;
import entity.Friend;
import entity.Message;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @descriptions: 聊天记录实现类
 * @author: ZQ
 * @date: 2023/3/6 16:00
 */
@Service
public class MessageServiceImp implements MessageService {

    @Resource
    private MessageMapper messageMapper;
    @Resource
    private FriendMapper friendMapper;

    /**
     * @descriptions 保存聊天记录
     * @author ZQ
     * @date 2023/3/1 14:35
     * @param userId
     * @param friendId
     * @param text
     * @param type
     * @return void
     */
    @Override
    public void storeMessage(String userId, String friendId, String text, String type) {
        // 获取当前时间
        Date date = new Date();
        // 查询好友信息
        Friend friend = friendMapper.getFriend(Integer.parseInt(userId),Integer.parseInt(friendId));
        // 查询聊天记录
        Message message = messageMapper.readMessageBySessionId(friend.getSessionId());
        // 查询发送对象好友信息
        Friend friend1 = friendMapper.getFriend(Integer.parseInt(friendId),Integer.parseInt(userId));
        // 未熟读+1
        Integer i = friend1.getUnread() + 1;
        // 发送信息对象修改最后消息
        friendMapper.updateFriendById(friend.getSessionId(),friend.getFriendId(),text,date);
        // 接收信息对象修改最后消息
        friendMapper.updateFriendByIds(friend.getSessionId(),friend.getMyId(),text,date,i);
        // 创建Message
        Message message1 = new Message();
        // 判断聊天记录是否为空
        if (message != null) {
            // 获取当前时间分钟
            SimpleDateFormat format = new SimpleDateFormat("mm");
            String format1 = format.format(date);
            String format2 = format.format(message.getSendTime());
            // 计算差值
            Integer time = Integer.parseInt(format1) - Integer.parseInt(format2);
            // 判断差值是否小于3 小于3 isWithdrawn = 1,大于3 isWithdrawn = 0
            if (time < 3){
                message1.setIsWithdrawn(1);
            } else {
                message1.setIsWithdrawn(0);
            }
        } else {
            //聊天记录为空 isWithdrawn = 0
            message1.setIsWithdrawn(0);
        }
        message1.setSessionId(friend.getSessionId());
        message1.setSenderId(Integer.parseInt(userId));
        message1.setReceiverId(Integer.parseInt(friendId));
        message1.setSendTime(date);
        message1.setContent(text);
        message1.setMessageType(type);
        message1.setCreateTime(date);
        message1.setUpdateTime(date);
        message1.setDelFlag(0);
        // 添加聊天记录
        messageMapper.insertMessage(message1);
    }
}